//
//  ModifyDataViewControlle.m
//  HeSaid
//
//  Created by MWJ on 15/5/4.
//  Copyright (c) 2015年 MWJ. All rights reserved.
//

#import "ModifyDataViewControlle.h"
#import "AppDelegate.h"
#import "PersonViewController.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#define personalDataURL @"http://app.jiwaipro.com:8888/hesaid/index.php/HeSaid/PersonalCenter"  //个人中心
#define headPortraitURL @"http://app.jiwaipro.com:8888/hesaid/index.php/HeSaid/uploadingheadPortrait"  //头像
#define modifyDataURL @"http://app.jiwaipro.com:8888/hesaid/index.php/HeSaid/modify"  //修改资料

@interface ModifyDataViewControlle (){
    NSDictionary *modifyDic;
    NSMutableArray *modifyArray;
    NSString *modifystr;
    NSDictionary *personDic;
    NSMutableArray *personArray;
    AppDelegate *app;
    UIAlertView *_alert;
}

@end

@implementation ModifyDataViewControlle

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title=@"修改资料";
    app = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    modifyArray = [NSMutableArray array];
    
    //头像形状为圆形
    self.headportraitImage.layer.masksToBounds = YES;
    self.headportraitImage.layer.cornerRadius = self.headportraitImage.bounds.size.width/2;
    //性别选择
    [self.sex addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    //更改头像
    self.headportraitImage.userInteractionEnabled = YES;
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(photoTapped)];
    [self.headportraitImage addGestureRecognizer:singleTap];//点击图片事件
    //加载信息
    NSString *poststr =[NSString stringWithFormat:@"user_id=%@",app.user_id];
    [self londingPath:personalDataURL Str:poststr];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 修改头像
-(void)photoTapped{
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    imagePicker.delegate = self;
    imagePicker.allowsEditing = YES;
    
    UIActionSheet* actionSheet = [[UIActionSheet alloc]
                                  initWithTitle:@"请选择文件来源"
                                  delegate:self
                                  cancelButtonTitle:@"取消"
                                  destructiveButtonTitle:nil
                                  otherButtonTitles:@"拍照",@"本地相册",nil];
    [actionSheet showInView:self.view];
    
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    switch (buttonIndex) {
        case 0://照相机
        {   if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
            UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
            imagePicker.delegate = self;
            imagePicker.allowsEditing = YES;
            imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
            //            [self presentModalViewController:imagePicker animated:YES];
            [self presentViewController:imagePicker animated:YES completion:nil];
        }else{
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"提示" message:@"NO Camera" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }
            
        }
            break;
            
        case 1://本地相簿
        {
            UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
            imagePicker.delegate = self;
            imagePicker.allowsEditing = YES;
            imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            
            [self presentViewController:imagePicker animated:YES completion:nil];
        }
            break;
            
        default:
            break;
    }
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];
    [self performSelector:@selector(saveImage:)  withObject:img afterDelay:0.5];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)saveImage:(UIImage *)image {
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *imageFilePath = [documentsDirectory stringByAppendingPathComponent:@"selfPhoto.jpg"];
    success = [fileManager fileExistsAtPath:imageFilePath];
    if(success) {
        success = [fileManager removeItemAtPath:imageFilePath error:&error];
    }
    UIImage *smallImage = [self thumbnailWithImageWithoutScale:image size:CGSizeMake(85, 85)];
    [UIImageJPEGRepresentation(smallImage, 1.0f) writeToFile:imageFilePath atomically:YES];//写入文件
    UIImage *Image=[UIImage imageWithContentsOfFile:imageFilePath];//写入文件
    self.headportraitImage.image=Image;
    NSData *data = UIImageJPEGRepresentation(self.headportraitImage.image, 1.0);
    NSURL *url=[NSURL URLWithString:headPortraitURL];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    request.delegate = self;
    [request setData:data  withFileName:@"tmp.jpg" andContentType:@"image/jpg" forKey:@"headPortrait"];
    [request setPostValue:app.user_id forKey:@"user_id"];
    [request setTag:3];
    [request startAsynchronous];
}
-(void)request:(ASIHTTPRequest *)request didReceiveData:(NSData *)data{
    NSString *json=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:NSUTF8StringEncoding error:nil];
    NSString *str=dic[@"key"];
    
    if ([str isEqualToString:@"success"]) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"touxiangAPI" object:nil];
    }
}
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (UIImage *)thumbnailWithImageWithoutScale:(UIImage *)image size:(CGSize)asize
{
    UIImage *newimage;
    if (nil == image) {
        newimage = nil;
    }
    else{
        CGSize oldsize = image.size;
        CGRect rect;
        if (asize.width/asize.height > oldsize.width/oldsize.height) {
            rect.size.width = asize.height*oldsize.width/oldsize.height;
            rect.size.height = asize.height;
            rect.origin.x = (asize.width - rect.size.width)/2;
            rect.origin.y = 0;
        }
        else{
            rect.size.width = asize.width;
            rect.size.height = asize.width*oldsize.height/oldsize.width;
            rect.origin.x = 0;
            rect.origin.y = (asize.height - rect.size.height)/2;
        }
        UIGraphicsBeginImageContext(asize);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
        UIRectFill(CGRectMake(0, 0, asize.width, asize.height));//clear background
        [image drawInRect:rect];
        newimage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    return newimage;
}

#pragma mark - 加载信息
-(void)londingPath:(NSString *)path Str:(NSString *)string{
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        personArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        [self performSelectorOnMainThread:@selector(refreshData:) withObject:personArray waitUntilDone:YES];
    }];
}
-(void)refreshData:(NSMutableArray *)sender{
    for (NSDictionary *dic in personArray) {
        self.phone.text= [NSString stringWithFormat:@"%@",dic[@"user_phone"]];
        self.sexLabel.text = [NSString stringWithFormat:@"%@",dic[@"user_sex"]];
        NSString *headportrait = [NSString stringWithFormat:@"%@",dic[@"user_HeadPortrait"]];
        NSURL *url=[NSURL URLWithString:headportrait];
        self.headportraitImage.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
    }
}
#pragma mark - “修改”按钮执行方法
-(void)londingPath1:(NSString *)path Str1:(NSString *)string{
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        modifystr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        [self performSelectorOnMainThread:@selector(refreshData1:) withObject:modifystr waitUntilDone:YES];
    }];
}
-(void)refreshData1:(NSMutableArray *)sender{
    int intstr = [modifystr intValue];
    if (intstr == 1) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"修改成功" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        _alert = alert;
        [alert show];
    }else{
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"修改失败" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }

}
#pragma mark - 提示框的点击事件

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==0&&alertView==_alert) {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        PersonViewController *personVC = [storyboard instantiateViewControllerWithIdentifier:@"personViewController"];
        [self.navigationController pushViewController:personVC animated:YES];
    }
}
-(void)refreshData{
    
}
#pragma mark - 选择控制器的点击事件
-(void)segmentAction:(UISegmentedControl *)Sex{
    
    NSInteger Index = Sex.selectedSegmentIndex;
    switch (Index) {
        case 0:
            self.sexLabel.text=@"男";
            break;
        case 1:
            self.sexLabel.text=@"女";
            break;
        default:
            break;
    }
}

#pragma mark - 点击“修改”按钮
- (IBAction)modify:(id)sender {
    //    [self Modifyperson];
    NSString *poststr =[NSString stringWithFormat:@"user_id=%@&user_sex=%@",app.user_id,self.sexLabel.text];
    [self londingPath1:modifyDataURL Str1:poststr];
}
@end
